﻿/*
 * *******************************************************
 *
 * 作者：hzy
 *
 * 开源地址：https://gitee.com/hzy6
 *
 * *******************************************************
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace HZY.IOT.SocketService.Core
{
    using SuperSocket;
    using SuperSocket.Server;
    using System.Text;

    /// <summary>
    /// 基本 AppSession
    /// </summary>
    public class BaseAppSession : AppSession
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public virtual ValueTask SendAsync(ReadOnlyMemory<byte> data)
        {
            return this.Channel.SendAsync(data);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public virtual ValueTask SendAsync(string data)
        {
            return this.SendAsync(Encoding.UTF8.GetBytes(data));
            //return this.SendAsync(new ArraySegment<byte>(Tools.mysendb(data)));
        }
    }

    /// <summary>
    /// Socket 扩展
    /// </summary>
    public static class SocketExtensions
    {
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="asyncSessionContainer"></param>
        /// <param name="data"></param>
        /// <param name="critera"></param>
        /// <returns></returns>
        public static async ValueTask SendAsync<TSession>(this IAsyncSessionContainer asyncSessionContainer, string data, Predicate<TSession> critera = null)
            where TSession : BaseAppSession
        {
            var sessions = await asyncSessionContainer.GetSessionsAsync(critera);

            foreach (var item in sessions)
            {
                await item.SendAsync(data);
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="asyncSessionContainer"></param>
        /// <param name="data"></param>
        /// <param name="critera"></param>
        /// <returns></returns>
        public static async ValueTask SendAsync<TSession>(this IAsyncSessionContainer asyncSessionContainer, ReadOnlyMemory<byte> data, Predicate<TSession> critera = null)
            where TSession : BaseAppSession
        {
            var sessions = await asyncSessionContainer.GetSessionsAsync(critera);

            foreach (var item in sessions)
            {
                await item.SendAsync(data);
            }
        }














    }
}
